use md5::{Digest, Md5};
use play_api::*;
use uuid::Builder;

pub struct OfflinePlayer;
pub trait Name2UUID {
    fn name2uuid(name: &str) -> PlayerUUID;
}
impl OfflineAuth for OfflinePlayer {
    fn to_auth(name: &str, uuid: Option<PlayerUUID>) -> AuthInfo {
        let uuid = uuid.unwrap_or_else(|| Self::name2uuid(name));
        AuthInfo {
            username: name.to_string(),
            uuid,
            access_token: "".to_string(),
            refresh_token: "".to_string(),
            is_online: false,
        }
    }
}
impl Name2UUID for OfflinePlayer {
    fn name2uuid(name: &str) -> PlayerUUID {
        let full_string = format!("OfflinePlayer:{}", name);
        let mut hasher = Md5::new();
        hasher.update(full_string);
        let hash = hasher.finalize();
        let mut bytes: [u8; 16] = hash.into();
        bytes[6] = (bytes[6] & 0x0F) | 0x30; // 版本 3
        bytes[8] = (bytes[8] & 0x3F) | 0x80; // 变体 2
        let mut b = Builder::from_bytes(bytes);
        b.set_version(uuid::Version::Md5)
            .set_variant(uuid::Variant::RFC4122);
        b.into_uuid()
    }
}
